package com.dm.cloud.configurations;

import org.apache.logging.log4j.util.Strings;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;

@Configuration
public class Oauth2Utils {

    private static DefaultTokenServices defaultTokenServices;

    public Oauth2Utils(DefaultTokenServices defaultTokenServices){
        this.defaultTokenServices = defaultTokenServices;
    }

    public static UserDetails getByAuthorization(String authorization){
        String token = getTokenStr(authorization);
        OAuth2Authentication auth2Authentication = defaultTokenServices.loadAuthentication(token);
        User u = (User)auth2Authentication.getUserAuthentication().getPrincipal();
        return u;
    }

    /**
     * 从前端的信息中解析token信息
     * @param authorization
     * @return
     */
    private static String getTokenStr(String authorization){
        //多出一个空格
//        Bearer b56117fd-01d9-4479-8a6e-4a3bd0351c74
        if(null == authorization){
            return Strings.EMPTY;
        }
        authorization = authorization.substring(OAuth2AccessToken.BEARER_TYPE.length() +1).trim();

        int commaIndex = authorization.indexOf(',');
        if(commaIndex>0){
            authorization = authorization.substring(0,commaIndex);
        }
        return authorization;
    }
}
